import React, {Component} from 'react';
import lotteryContract from './api/deploy';
import web3 from './util/web3utils';
import CardExampleCard from './web/ui';

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            manager: '',
            players: '',
            amount: '',
            round: '',
            playerCount: '',
            currentAccount: '',
            isPlaying:false,
            isKaiJiangZhong:false,
            isDrawingBack:false,
            buttonControl:'',
        };
    }

    // 组件初始化时自动执行的方法
    async componentDidMount() {
        let accounts = await web3.eth.getAccounts();
        let manager = await lotteryContract.methods.getManager().call();
        let winner = await lotteryContract.methods.getWinner().call();
        let players = await lotteryContract.methods.getPlayers().call();
        let amount = await lotteryContract.methods.getBalance().call();
        let round = await lotteryContract.methods.getRound().call();
        let playerCount = await lotteryContract.methods.getPlayerCount().call();

        this.setState({
            currentAccount: accounts[0],
            manager,
            winner,
            players,
            amount: web3.utils.fromWei(amount, 'ether'),
            round,
            playerCount
        });
        if (manager === accounts[0]) {
            //管理员则显示
            this.setState({buttonControl : 'inline'})
        } else {
            this.setState({buttonControl : 'none'})
        }

    }
    /*
    投注会改变合约状态，所以使用send方法（新手册请参见sendTransaction函数），我们只需要填两个参数：
    投注的账户
    投注的金额，我们限定为1 ether，这里要注意，不要使用’ether'单位，这里是js，没有这个单位。
    我们在每次执行前后都使用了一个标志位isPlaying来标识当前应用的状态，用于控制按钮状态。
    每次执行执行结果返回后自动刷新浏览器，显示最新结果。
    记得使用try catch捕捉错误异常。
    */


    play = async () => {
        let accounts = await web3.eth.getAccounts();
        //调用合约的play方法
        this.setState({isPlaying:true});
        try {
            await  lotteryContract.methods.play().send({
                from: accounts[0],
                value: 1 * 10 ** 18,
            });
            alert('投注成功!');
            this.setState({isPlaying:false});
            window.location.reload(true);
        } catch (e) {
            alert('投注失败！');
            this.setState({isPlaying:false});
        }

    };
    draw = async () => {
        //判断一下，如果已经点击了，但是没有处理完成，那么不允许再次调用合约的play方法
        this.setState({isDrawing : true})

        //1. 调用合约的play方法
        try {
            let accounts = await web3.eth.getAccounts()
            await lotteryContract.methods.kaijiang().send({
                from: accounts[0], //重新获取一次比较稳妥
                // value: 1 * 10 ** 18 //wei //开奖不需要转钱
            })
            //弹框
            let winner = await lotteryContract.methods.winner().call()
            this.setState({winner})
            // alert(`本期赢家: ${this.state.winner}`)
            alert(`本期赢家: ${winner}`)
            this.setState({isDrawing : false})

            //这是为了自动刷新页面,可以不加，然后手动刷新
            window.location.reload(true)
        } catch (e) {
            this.setState({isDrawing : false})
            alert('开奖失败!')
            console.log(e)
        }
    }
    drawback = async () => {
        console.log("drawback button clicked!!!!!!")
        this.setState({isDrawingBack : true})
        try {
            let accounts = await web3.eth.getAccounts();
            await lotteryContract.methods.drawback().send({
                from: accounts[0],
            })

            alert("drawback successfully!");
            this.setState({isDrawingBack : false})
            window.location.reload(true);
        } catch (e) {
            this.setState({isDrawingBack : false})
            alert(`drawback failed!, ${e}`);
        }
    }
    //只要有一个按钮被点击了，那么三个按钮都应该被disable
    isDisable = () => {
        return this.state.isPlaying || this.state.isKaiJiangZhong || this.state.isDrawingBack
    }

    render() {

        return (
            <div className="App">
                <CardExampleCard
                    manager={this.state.manager}//owner
                    currentAccount={this.state.currentAccount}//当前玩家
                    winner={this.state.winner}//赢家
                    players={this.state.players}//玩家总数
                    amount={this.state.amount}//奖金池
                    round={this.state.round}//第几期
                    playerCount={this.state.playerCount}//参与人数
                    play={this.play}//投注
                    draw={this.draw}//开奖
                    drawback={this.drawback}//退款
                    isPlaying={this.isPlaying}
                    isKaiJiangZhong={this.isDrawing}
                    isDrawingBack={this.isDrawingBack}
                    buttonControl={this.state.buttonControl}
                    isDisable={this.isDisable}
                />
            </div>
        );
    }
}

export default App;
